<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.name"
          clearable
          placeholder="名称"
          style="width: 185px" class="filter-item"
          @keyup.enter.native="crud.toQuery"/>
        <el-input
          v-model="query.code"
          clearable
          placeholder="编码"
          style="width: 185px" class="filter-item"
          @keyup.enter.native="crud.toQuery"/>
        <rrOperation :crud="crud"/>
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission"/>
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="550px"
      >
        <el-form ref="form" v-loading="crud.editLoading" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" style="width: 370px"/>
          </el-form-item>
          <el-form-item label="编码" prop="code">
            <el-input v-model="form.code" :disabled="form.id != null" style="width: 370px"/>
          </el-form-item>
          <el-form-item label="实现类" prop="ruleClass">
            <el-input v-model="form.ruleClass" style="width: 370px"/>
          </el-form-item>
          <el-form-item label="参数" prop="params">
            <div v-for="(param, index) in dynamicParams" :key="index" style="display: flex;width: 392px">
              <el-input placeholder="请输入参数key" v-model:value="param.label" style="width: 182px;"/>
              <el-input placeholder="请输入参数value" v-model:value="param.value"
                        style="width: 182px; margin-left: 6px;margin-top: 2px;"/>
              <el-button
                v-if="dynamicParams.length > 1"
                type="text"
                icon="el-icon-remove-outline"
                @click="removeParam(param)"
                style="font-size:22px;"/>
            </div>
            <div>
              <el-button type="dashed" icon="el-icon-plus" style="width: 370px;margin-top: 5px;" @click="addParam">
                新增
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button
            :loading="crud.status.cu == 2"
            type="primary"
            @click="crud.submitCU"
          >确认
          </el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        highlight-current-row
        stripe
        :data="crud.data"
        size="small"
        style="width: 100%"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="name" label="名称"/>
        <el-table-column prop="code" label="编码"/>
        <el-table-column prop="ruleClass" label="实现类"/>
        <el-table-column prop="params" label="参数"/>
        <el-table-column
          v-permission="['admin','sys_fill_rule:edit','sys_fill_rule:del']"
          label="操作"
          width="300px"
          align="center"
        >
          <template slot-scope="scope">
            <div style="display: inline-block">
              <udOperation
                :data="scope.row"
                :permission="permission"
              />
            </div>
            <el-tooltip content="功能测试" effect="dark" placement="top">
              <el-button
                size="mini"
                type="success"
                icon="el-icon-magic-stick"
                style="display: inline-block"
                @click="handleTest(scope.row.code)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination/>
    </div>
  </div>
</template>

<script>
import crudSysFillRule, {test} from '@/api/system/sys_fill_rule'
import CRUD, {crud, form, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import DateRangePicker from '@/components/DateRangePicker'

const defaultForm = {
  id: null,
  name: null,
  code: null,
  ruleClass: null,
  params: null,
}
export default {
  name: 'SysFillRule',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    DateRangePicker
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({
      title: '系统编码规则',
      url: 'sys/fill_rules',
      idField: 'id',
      sort: 'id DESC',
      crudMethod: {...crudSysFillRule}
    })
  },
  data() {
    return {
      permission: {
        add: ['admin', 'sys_fill_rule:add'],
        edit: ['admin', 'sys_fill_rule:edit'],
        del: ['admin', 'sys_fill_rule:del']
      },
      rules: {
        name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
        code: [{required: true, message: '编码不能为空', trigger: 'blur'}],
        ruleClass: [{required: true, message: '实现类不能为空', trigger: 'blur'}]
      },
      queryTypeOptions: [
        {key: 'name', display_name: '名称'},
        {key: 'code', display_name: '编码'}
      ],
      dynamicParams: []
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterToEdit]() {
      this.dynamicParams = []
      const formParams = this.form.params
      if (formParams && formParams.indexOf('{') == 0) {
        let jsonObj = JSON.parse(formParams);
        Object.keys(jsonObj).forEach((key) => {
          this.dynamicParams.push({label: key, value: jsonObj[key]});
        });
      }
    },
    [CRUD.HOOK.beforeToAdd]() {
      this.dynamicParams = []
    },
    [CRUD.HOOK.beforeSubmit]() {
      let obj = {};
      if (this.dynamicParams.length > 0) {
        this.dynamicParams.forEach((item) => {
          obj[item['label']] = item['value'];
        });
      }
      this.form.params = obj == null || obj == '' ? '' : JSON.stringify(obj)
    },
    addParam() {
      this.dynamicParams.push({
        label: '',
        value: '',
      });
    },
    removeParam(item) {
      let index = this.dynamicParams.indexOf(item);
      if (index !== -1) {
        this.dynamicParams.splice(index, 1);
      }
    },
    handleTest(code) {
      test(code).then(data => {
        this.$alert('生成结果：' + data,
          '规则功能测试', {
            dangerouslyUseHTMLString: true,
            type: 'success'
          })
        }
      )
    }
  }
}
</script>

<style scoped></style>
